import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class MyClassLoader extends ClassLoader {

	private String javaFileName;
	private String classFileName;

	public MyClassLoader(String javaFileName, String classFileName) {
		this.javaFileName = javaFileName;
		this.classFileName = classFileName;

	}

	private byte[] getBytes(String classFileName) throws IOException {

		File file = new File(classFileName);

		long len = file.length();

		byte[] array = new byte[(int) len];

		FileInputStream fin = new FileInputStream(file);

		int r = fin.read(array);
		if (r != len) {
			fin.close();
			throw new IOException("Can`t read all file!");
		}
		fin.close();
		return array;
	}

	private boolean compile(String javaFile) throws IOException {

		System.out.println("compiling " + javaFile);

		Process p = Runtime.getRuntime().exec("javac " + javaFile);
		try {
			p.waitFor();
		} catch (InterruptedException ie) {
			System.err.println("Interruption occured!");
		}
		int ret = p.exitValue();

		return ret == 0;
	}

	protected synchronized Class<?> findClass(String name)
			throws ClassNotFoundException {
		Class<?> clas = null;

		File javaFile = new File(javaFileName);
		File classFile = new File(classFileName);

		if ((javaFile.exists() && !classFile.exists())
				|| (javaFile.lastModified() > classFile.lastModified())) {
			try {
				if (!compile(javaFileName) || !classFile.exists()) {
					throw new ClassNotFoundException("Compile failed: "
							+ javaFileName);
				}
			} catch (IOException io) {
				throw new ClassNotFoundException("Something else "
						+ io.toString());
			}
		}

		try {
			byte[] array = getBytes(classFileName);

			clas = defineClass(name, array, 0, array.length);

		} catch (IOException io1) {
			System.out.println(io1.getMessage());
			System.err.println("getBytes! Cannot find the class!");
		}

		System.out.println("Define class: " + clas);
		if (clas != null) {
			resolveClass(clas);
		} else
			throw new ClassNotFoundException("Final exception");

		return clas;
	}

}
